import React, {
  memo,
  useEffect,
  useState,
  createElement,
  useCallback,
} from "react";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { Comment, Tooltip, Avatar, message } from "antd";
import { LikeFilled, LikeOutlined } from "@ant-design/icons";

import HYPagination from "@/components/pagination";
import ThemeHeader from "@/components/theme-header";

import { changeCommentTotal } from "../../store/actionCreator";
import { changeIsShow } from "@/components/theme-login/store";
import { sendSongComment } from "@/service/player";
import { getCount, relativeTime } from "@/utils/format-utils";
import { reqSongComment } from "@/api/song";
import ThemeComment from "@/components/theme-comment";
import { sendLikeComment } from "@/service/songs";
import sty from "./sty.module.css";
import cs from "classnames";
function SongComment(props) {
  const { songId } = props;
  const [comment, setComment] = useState([]);
  const [hotComments, setHotComments] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [flag, setFlag] = useState(false);
  const [liked, setLiked] = useState([]); // 歌曲的点赞状态
  // const [total, setTotal] = useState(0)
  const currentSongId = songId;
  // redux hook
  const dispatch = useDispatch();
  const { isLogin, cookie, avatarUrl } = useSelector(
    (state) => ({
      isLogin: state.getIn(["loginState", "isLogin"]),
      cookie: state.getIn(["loginState", "cookie"]),
      avatarUrl: state.getIn(["loginState", "profile", "avatarUrl"]),
    }),
    shallowEqual
  );

  // other hooks
  useEffect(() => {
    reqSongComment(songId).then((res) => {
      console.log(res);
      if (res.code === 200) {
        setComment(res.comments);
        setHotComments(res.hotComments);
        setTotal(res.total);
        dispatch(changeCommentTotal(res.total));
      }
    });

  }, [dispatch, songId]);

  // other handle
  function formatDate(time = Date().now()) {

    var date = new Date(time + 8 * 3600 * 1000); // 增加8小时

    return date.toJSON().substr(0, 19).replace("T", " ");
  }



  // 点赞评论
  const likeComment = (index, data) => {
    // if (liked[index].count >= 1) return
    // 登录鉴权
    if (!isLogin) {
      // 没登陆
      dispatch(changeIsShow(true));
    }
    if (!flag) {
      liked[index].liked = true;
      liked[index].count += 1;
      setLiked(liked);

      sendLikeComment(currentSongId, data.commentId, 1, cookie).then((res) => {
        console.log("res :>>>", res);
        if (res.code === 200) message.success("点赞成功");
        else message.success("请稍后再试");
      });
    } else {
      liked[index].liked = false;
      liked[index].count -= 1;
      setLiked(liked);
      setFlag(true);

      sendLikeComment(data.commentId, 0, cookie).then((res) => {
        if (res.code === 200) {
          message.success("取消点赞成功");
        }
      });
    }
    setFlag(!flag);
  };

  // 分页
  const changePage = useCallback(
    (currentPage) => {
      setCurrentPage(currentPage);
      // offset=(当前页数-1)*limit
      const targePageCount = (currentPage - 1) * 20;
      reqSongComment(currentSongId, 20, targePageCount).then((res) => {
        setComment(res.comments);
      });
    },
    [currentSongId]
  );

  // template html action
  // 点赞HTML
  const getLikeTemplateAction = (item, index) => {
    liked.push({
      liked: item.liked,
      count: item.likedCount,
    });

    return [
      <Tooltip key="comment-basic-like" title="Like" className="comment-like">
        <span onClick={() => likeComment(index, item)}>
          {createElement(
            liked[index].liked === true ? LikeFilled : LikeOutlined
          )}
          <span className="comment-action">{getCount(liked[index].count)}</span>
        </span>
      </Tooltip>,
    ];
  };
  // 评论歌曲校验(获取焦点)
  const commentSongcheckout = () => {
    // 没登录
    if (!isLogin) dispatch(changeIsShow(true));
  };

  // 评论成功
  const commentCallbackOk = (value) => {
    sendSongComment(currentSongId, value, cookie).then((res) => {
      if (res.code === 200) {
        message.success("评论成功").then(() => {
          reqSongComment(currentSongId).then((res) => {
            setComment(res.comments);
            setTotal(res.total);
          });
        });
      }
    });
  };

  return (
    <div className={sty.root}>
      <ThemeHeader title="评论" />
      {/* 评论内容 */}
      <ThemeComment
        onFocus={() => commentSongcheckout()}
        callbackOk={(value) => commentCallbackOk(value)}
        isLogin={isLogin}
        photo={avatarUrl}
      />
      {/* 精彩评论 */}

      <div className={sty.commentHeader}>精彩评论</div>
      {hotComments &&
        hotComments.map((item, index) => {
          return (
            <Comment
              // actions={getLikeTemplateAction(item, index)}
              key={item.commentId}
              author={item.user.nickname}
              avatar={<Avatar src={item.user.avatarUrl} alt="Han Solo" />}
              content={<p>{item.content}</p>}
              datetime={
                <Tooltip title={formatDate(item.time)}>
                  {relativeTime(item.time)}
                </Tooltip>
              }
            />
          );
        })}

      {/* 最新评论 */}

      <div className={cs(sty.commentHeader, sty.top)}>最新评论</div>
      {comment &&
        comment.map((item, index) => {
          return (
            <Comment
              actions={getLikeTemplateAction(item, index)}
              key={item.commentId}
              author={item.user.nickname}
              avatar={<Avatar src={item.user.avatarUrl} alt="Han Solo" />}
              content={<p>{item.content}</p>}
              datetime={
                <Tooltip title={formatDate(item.time)}>
                  {formatDate(item.time)}
                </Tooltip>
              }
            />
          );
        })}

      {/* 分页 */}
      <HYPagination
        currentPage={currentPage}
        pageSize={20}
        total={total}
        onPageChange={(currentPage) => changePage(currentPage)}
      />
    </div>
  );
}

export default memo(SongComment);
